package com.houger.facade;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.houger.utils.RedissonLock;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Houger.
 * @date 2023年11月29日 16:29.
 */
@RestController
@RequestMapping("/user")
public class UserFacade {

    @Resource
    RedisTemplate<String,String> redisTemplate;
    @Resource
    RedissonLock redissonLock;

    @PostMapping("/queryByName")
    public String queryByName(@RequestBody UserReq userReq) {
        String lockKey = userReq.getName()+UUID.fastUUID();
        if(redissonLock.tryLock(lockKey,200, TimeUnit.MILLISECONDS)){
            try {
                final Boolean hasKey = redisTemplate.hasKey(userReq.getName());
                if (!Boolean.TRUE.equals(hasKey)){
                    userReq.setId(1L);
                    userReq.setHobby("编程");
                    redisTemplate.opsForHash().putAll(userReq.getName(), BeanUtil.beanToMap(userReq));
                    redisTemplate.expire(userReq.getName(),600, TimeUnit.SECONDS);
                    return JSONObject.toJSONString(userReq);
                }
                final Map<Object, Object> entries = redisTemplate.opsForHash().entries(userReq.getName());
                userReq = BeanUtil.toBean(entries, UserReq.class);
                return JSONObject.toJSONString(userReq);
            }finally {
                redissonLock.unlock(lockKey);
            }
        }else{
            throw new RuntimeException("请求过于频繁，请稍后重试");
        }
    }
}

@Data
class UserReq {
    private Long id;
    private String name;
    private String hobby;
}